package cn.hanyx.coder.design.pattern.creational.factory.method.demo02;

import cn.hanyx.coder.design.pattern.creational.factory.method.demo01.factory.*;
import cn.hanyx.coder.design.pattern.creational.factory.simple.demo01.IRuleConfigParser;
import cn.hanyx.coder.design.pattern.creational.factory.simple.demo01.RuleConfig;
import org.apache.commons.lang3.StringUtils;

/**
 * RuleConfigSource
 * 根据配置文件的后缀（json、xml、yaml、properties），
 * 选择不同的解析器（JsonRuleConfigParser、XmlRuleConfigParser……），
 * 将存储在文件中的配置解析成内存对象 RuleConfig
 *
 * @author hanyx
 * @date 2020/07/14
 */
public class RuleConfigSource {

    public RuleConfig load(String ruleConfigFilePath) throws Exception {
        String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);

        IRuleConfigParserFactory parserFactory = RuleConfigParserFactoryMap.getParserFactory(ruleConfigFileExtension);
        IRuleConfigParser parser = parserFactory.createParser();

        String configText = "abc";
        //从ruleConfigFilePath文件中读取配置文本到configText中
        RuleConfig ruleConfig = parser.parse(configText);
        return ruleConfig;
    }

    private String getFileExtension(String filePath) {
        //...解析文件名获取扩展名，比如rule.json，返回json
        String[] strs = StringUtils.split(filePath, ".");
        return strs[1];
    }


    public static void main(String[] args) throws Exception {
        RuleConfigSource source = new RuleConfigSource();
        RuleConfig config = source.load("hello.yaml");
    }
}
